package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cdtu.healthserver.domain.Test;
import cn.edu.cdtu.healthserver.domain.TestType;
import cn.edu.cdtu.healthserver.service.TestService;
import cn.edu.cdtu.healthserver.service.impl.TestServiceImplementation;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;

import com.google.gson.Gson;

/**
 * Servlet implementation class TesServletForClient
 */
@WebServlet("/TestServletForClient")
public class TestServletForClient extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private TestService testService;
    private Gson gson;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServletForClient() {
        super();
        // TODO Auto-generated constructor stub
        testService = new TestServiceImplementation();
        gson = new Gson();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String option = request.getParameter(
				ConnectUtil.HealthTestPargrams.Option.HEALTH_TEST_OPTION);
		if(ConnectUtil.HealthTestPargrams.Option
				.OptionValue.HEALTH_TEST_OPTION_GET_TEST.equals(option)){
			this.getTestList(request, response);
		}
	}
	
	private void getTestList(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setContentType(ConnectUtil.ContentTypeString.jSON_STRING);
		String testTypeJsonString = request.getParameter(
				ConnectUtil.HealthTestPargrams.Pargram.SELECT_TEST_TYPE);
		TestType testType = gson.fromJson(testTypeJsonString, TestType.class);
		List<Test> testList = testService.getTests(testType, false);
		PrintWriter writer = response.getWriter();
		writer.println(gson.toJson(testList));
		writer.flush();
		writer.close();
	}

}
